import os
import json
import re
import random
import math
import time
import base64
import requests
import psutil
from botpy import logging
from PIL import Image
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from botpy.message import GroupMessage, Message
from tools import player_id, send_message, bag_number, send_pic_message
from battle import attribute_count

async def my_bag(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid
    elif hasattr(message.author, 'user_openid'):
        number = message.author.user_openid
    uid = await player_id(number)
    page = re.search(r'\d+', message.content)
    page_size = 20
    if page:
        page = int(page.group())
    else:
        page = 1
 
    with open(f"data/bag/{uid}.txt", 'r') as f:
        data = json.load(f)
    items = data['背包']
    search = False
    if "背包搜索" in message.content:
        search = True
        word0 = message.content.split("背包搜索")[1]
        word = re.sub(r'\d+', '', word0)
        items = [item for item in items if word in item["名称"]]

    total_items = len(items)
    total_pages = (total_items + page_size - 1) // page_size

    if page < 1 or page > total_pages:
        return "\n【Error】页码错误\n只有[{}]页".format(total_pages)

    start_index = (page - 1) * page_size
    end_index = start_index + page_size
    items_to_display = items[start_index:end_index]

    txt = "\n===❈个人背包❈===\n————————————".format(data["nickname"])
    for item in items_to_display:
        if "·" in item['名称'] and "+" in item['名称']:
            item_name = item['名称'].split("+")[0]
        else:
            item_name = item['名称']
        txt += f"\n◈ [{item_name}] x {item['数量']}"

    if total_pages > 1:
        if not search:
            txt += f"\n————————————\n第{page}页，共{total_pages}页。发送[背包{page+1}]查看下一页。"
        else:
            txt += f"\n————————————\n第{page}页，共{total_pages}页。发送[背包搜索关键词{page+1}]查看下一页。"

    await send_message(message, 0, 1, txt)
    return


async def my_board(message):
    for process in psutil.process_iter():
        if "google-chrome" in process.name():
            return
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid
    elif hasattr(message.author, 'user_openid'):
        number = message.author.user_openid
    await attribute_count(message)
    uid = await player_id(number)
    with open(f"data/player/{uid}.txt", 'r') as f:
        data = json.load(f)
    with open(f"data/bag/{uid}.txt", 'r') as f:
        bag_data = json.load(f)
    service = Service('/usr/bin/chromedriver')
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')  # 无头模式，不需要显示图形界面
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument("--start-maximized")  # 最大化窗口
    options.add_argument("--window-size=1920,1080")  # 设置窗口大小为1920x1080
    driver = webdriver.Chrome(service=service, options=options)

    # 打开原始HTML文件并读取内容
    with open('图片文件/att.html', 'r') as file:
        html_content = file.read()
    html_content = html_content.replace('这里是名字', data["nickname"])
    html_content = html_content.replace('这里是UID', str(data["id"]))
    html_content = html_content.replace('一转', data.get("一转", "无"))
    html_content = html_content.replace('二转', data.get("二转", "无"))
    html_content = html_content.replace('三转', data.get("三转", "无"))
    html_content = html_content.replace('属性101', str(data["体质"].get("基础", "0")))
    html_content = html_content.replace('属性201', str(data["敏捷"].get("基础", "0")))
    html_content = html_content.replace('属性301', str(data["力量"].get("基础", "0")))
    html_content = html_content.replace('属性401', str(data["智力"].get("基础", "0")))
    html_content = html_content.replace('属性102', str(data["体质"].get("加点", "0")))
    html_content = html_content.replace('属性202', str(data["敏捷"].get("加点", "0")))
    html_content = html_content.replace('属性302', str(data["力量"].get("加点", "0")))
    html_content = html_content.replace('属性402', str(data["智力"].get("加点", "0")))
    add1 = round((data["体质"].get("加成", 0) / 5 + data["体质"].get("基础", 0) + data["体质"].get("加点", 0)) * (100 + data["体质"].get("加成", 0)) / 100 - data["体质"].get("基础", 0) - data["体质"].get("加点", 0), 1)
    add2 = round((data["敏捷"].get("加成", 0) / 5 + data["敏捷"].get("基础", 0) + data["敏捷"].get("加点", 0)) * (100 + data["敏捷"].get("加成", 0)) / 100 - data["敏捷"].get("基础", 0) - data["敏捷"].get("加点", 0), 1)
    add3 = round((data["力量"].get("加成", 0) / 5 + data["力量"].get("基础", 0) + data["力量"].get("加点", 0)) * (100 + data["力量"].get("加成", 0)) / 100 - data["力量"].get("基础", 0) - data["力量"].get("加点", 0), 1)
    add4 = round((data["智力"].get("加成", 0) / 5 + data["智力"].get("基础", 0) + data["智力"].get("加点", 0)) * (100 + data["智力"].get("加成", 0)) / 100 - data["智力"].get("基础", 0) - data["智力"].get("加点", 0), 1)
    add1 = round(add1, 1)
    if add1 == int(add1):
        add1 = int(add1)
    add2 = round(add2, 1)
    if add2 == int(add2):
        add2 = int(add2)
    add3 = round(add3, 1)
    if add3 == int(add3):
        add3 = int(add3)
    add4 = round(add4, 1)
    if add4 == int(add4):
        add4 = int(add4)
    html_content = html_content.replace('属性103', str(add1))
    html_content = html_content.replace('属性203', str(add2))
    html_content = html_content.replace('属性303', str(add3))
    html_content = html_content.replace('属性403', str(add4))
    add1 = data["体质"].get("躯体", 0)
    add2 = data["敏捷"].get("躯体", 0)
    add3 = data["力量"].get("躯体", 0)
    add4 = data["智力"].get("躯体", 0)
    add1 = round(add1, 1)
    if add1 == int(add1):
        add1 = int(add1)
    add2 = round(add2, 1)
    if add2 == int(add2):
        add2 = int(add2)
    add3 = round(add3, 1)
    if add3 == int(add3):
        add3 = int(add3)
    add4 = round(add4, 1)
    if add4 == int(add4):
        add4 = int(add4)
    html_content = html_content.replace('属性104', str(add1))
    html_content = html_content.replace('属性204', str(add2))
    html_content = html_content.replace('属性304', str(add3))
    html_content = html_content.replace('属性404', str(add4))
    html_content = html_content.replace('属性105', str(data["体质"].get("进化", "0")))
    html_content = html_content.replace('属性205', str(data["敏捷"].get("进化", "0")))
    html_content = html_content.replace('属性305', str(data["力量"].get("进化", "0")))
    html_content = html_content.replace('属性405', str(data["智力"].get("进化", "0")))
    html_content = html_content.replace('属性106', str(data["体质"].get("装备", "0")))
    html_content = html_content.replace('属性206', str(data["敏捷"].get("装备", "0")))
    html_content = html_content.replace('属性306', str(data["力量"].get("装备", "0")))
    html_content = html_content.replace('属性406', str(data["智力"].get("装备", "0")))
    html_content = html_content.replace('属性107', str(data["体质"].get("最终", "0")))
    html_content = html_content.replace('属性207', str(data["敏捷"].get("最终", "0")))
    html_content = html_content.replace('属性307', str(data["力量"].get("最终", "0")))
    html_content = html_content.replace('属性407', str(data["智力"].get("最终", "0")))
    name1 = bag_data["装备"].get("武器", "无").split("+")[0]
    name2 = bag_data["装备"].get("副手", "无").split("+")[0]
    name3 = bag_data["装备"].get("头肩", "无").split("+")[0]
    name4 = bag_data["装备"].get("上身", "无").split("+")[0]
    name5 = bag_data["装备"].get("腰部", "无").split("+")[0]
    name6 = bag_data["装备"].get("下身", "无").split("+")[0]
    name7 = bag_data["装备"].get("脚部", "无").split("+")[0]
    name8 = bag_data["装备"].get("项链", "无").split("+")[0]
    name9 = bag_data["装备"].get("手镯", "无").split("+")[0]
    name10 = bag_data["装备"].get("戒指", "无").split("+")[0]
    html_content = html_content.replace('武器名', str(name1))
    html_content = html_content.replace('副手名', str(name2))
    html_content = html_content.replace('头肩名', str(name3))
    html_content = html_content.replace('上身名', str(name4))
    html_content = html_content.replace('腰部名', str(name5))
    html_content = html_content.replace('下身名', str(name6))
    html_content = html_content.replace('脚部名', str(name7))
    html_content = html_content.replace('项链名', str(name8))
    html_content = html_content.replace('手镯名', str(name9))
    html_content = html_content.replace('戒指名', str(name10))
    html_content = html_content.replace('头像.jpg', f"{uid}_head.png")
    
    head_url = f"https://q.qlogo.cn/qqapp/102057736/{number}/640"
    response = requests.get(head_url)
    if response.status_code == 200:
    # 如果响应成功，将图片数据写入文件
        with open(f"临时图片/面板/{uid}_head.png", 'wb') as file:
            file.write(response.content)

    # 写入修改后的内容到新的HTML文件
    with open(f'临时图片/面板/{uid}_att.html', 'w') as file:
        file.write(html_content)
    # 获取当前运行目录
    current_folder = os.path.dirname(os.path.abspath(__file__))
    html_file_path = os.path.join(current_folder, f"临时图片/面板/{uid}_att.html")
    driver.get("file://" + html_file_path)
    driver.execute_script("document.body.style.zoom='100%'")
    # 定位具有特定CSS属性的元素
    background_image_box = driver.find_element(By.CSS_SELECTOR, ".background-image-box")
    # 获取元素的位置和大小
    box_location = background_image_box.location
    box_size = background_image_box.size
    # 截图并保存
    if os.path.exists(f"临时图片/面板/{uid}.png"):
        os.remove(f"临时图片/面板/{uid}.png")
    driver.save_screenshot(f"临时图片/面板/{uid}.png")
    # 关闭浏览器
    driver.quit()
    
    screenshot = Image.open(f"临时图片/面板/{uid}.png")
    image_width, image_height = screenshot.size
    # 计算裁剪框的右下角坐标，确保不超过图片边缘
    crop_right = min(box_location['x'] + box_size['width'], image_width)
    crop_bottom = min(box_location['y'] + box_size['height'], image_height)
    # 裁剪图像
    box_image = screenshot.crop((box_location['x'], box_location['y'], crop_right, crop_bottom))
    # 保存裁剪后的图像
    box_image.save(f"临时图片/面板/{uid}_final.png")
    # 尝试打开支持的图片格式
    with open(f"临时图片/面板/{uid}_final.png", "rb") as f:
        image_data = f.read()
    # 将图片数据编码为 base64 字符串
    base64_data = base64.b64encode(image_data).decode("utf-8")
    _log = logging.get_logger()
    if hasattr(message, 'group_openid'):
        media_0 = await message._api.post_group_file(
        group_openid=message.group_openid,
        file_type=1,
        url=None,
        srv_send_msg=False,
        file_data=base64_data
        )
        messageResult = await message._api.post_group_message(
        group_openid=message.group_openid,
        msg_type=7, 
        msg_id=message.id,
        msg_seq=1,
        content="",
        media=media_0
        )
        _log.info(messageResult)
    else:
        media_0 = await message._api.post_c2c_file(
        openid=message.author.user_openid,
        file_type=1,
        url=None,
        srv_send_msg=False,
        file_data=base64_data
        )
        messageResult = await message._api.post_c2c_message(
        openid=message.author.user_openid, 
        msg_type=7, 
        msg_id=message.id, 
        msg_seq=1,
        content="",
        media=media_0
        )
        _log.info(messageResult)
        
    return


async def my_attribute(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid
    elif hasattr(message.author, 'user_openid'):
        number = message.author.user_openid
    await attribute_count(message)
    uid = await player_id(number)
    with open(f"data/player/{uid}.txt", 'r') as f:
        data = json.load(f)

    body = ""
    blood = ""
    talent = ""
    if "天生大力" in data["体魄"] and "天生聪明" in data["体魄"] and "天生灵活" in data["体魄"] and "天生强壮" in data["体魄"]:
        data["体魄"].remove("天生大力")
        data["体魄"].remove("天生聪明")
        data["体魄"].remove("天生灵活")
        data["体魄"].remove("天生强壮")
        data["体魄"].append("天生全能")
    if "天生神力" in data["体魄"] and "天生聪慧" in data["体魄"] and "天生灵巧" in data["体魄"] and "天生强健" in data["体魄"]:
        data["体魄"].remove("天生神力")
        data["体魄"].remove("天生聪慧")
        data["体魄"].remove("天生灵巧")
        data["体魄"].remove("天生强健")
        data["体魄"].append("天生超能")
    if "斗战之体" in data["体魄"] and "神灵之体" in data["体魄"] and "瞬之体" in data["体魄"] and "轮回之体" in data["体魄"]:
        data["体魄"].remove("斗战之体")
        data["体魄"].remove("神灵之体")
        data["体魄"].remove("瞬之体")
        data["体魄"].remove("轮回之体")
        data["体魄"].append("混沌之体")
    if "斗战神体" in data["体魄"] and "仙灵之体" in data["体魄"] and "影之体" in data["体魄"] and "轮回神体" in data["体魄"]:
        data["体魄"].remove("斗战神体")
        data["体魄"].remove("仙灵之体")
        data["体魄"].remove("影之体")
        data["体魄"].remove("轮回神体")
        data["体魄"].append("混沌神体")
    if "苍天霸体" in data["体魄"] and "先天道体" in data["体魄"] and "末影黑体" in data["体魄"] and "荒古圣体" in data["体魄"]:
        data["体魄"].remove("苍天霸体")
        data["体魄"].remove("先天道体")
        data["体魄"].remove("末影黑体")
        data["体魄"].remove("荒古圣体")
        data["体魄"].append("混沌圣体")
    if "天生全能" in data["体魄"] and "天生超能" in data["体魄"]:
        data["体魄"].remove("天生全能")
        data["体魄"].remove("天生超能")
        data["体魄"].append("天生完美")
    if "混沌之体" in data["体魄"] and "混沌神体" in data["体魄"] and "混沌圣体" in data["体魄"]:
        data["体魄"].remove("混沌之体")
        data["体魄"].remove("混沌神体")
        data["体魄"].remove("混沌圣体")
        data["体魄"].append("混沌终焉")
    elif "混沌之体" in data["体魄"] and "混沌神体" in data["体魄"]:
        data["体魄"].remove("混沌之体")
        data["体魄"].remove("混沌神体")
        data["体魄"].append("混沌代言")
    for item in data["体魄"]:
        body += "【{}】".format(item)
    for item in data["血脉"]:
        blood += "【{}】".format(item)
    for item in data["天赋"]:
        talent += "【{}】".format(item)
    if body == "":
        body = "[无]"
    if blood == "":
        blood = "[无]"
    if talent == "":
        talent = "[无]"

    job = ""
    if "一转" in data:
        if data["一转"] == "盾守":
            job = "\n🛡️盾守🛡️"
        elif data["一转"] == "战士":
            job = "\n⚔️战士⚔️"
        elif data["一转"] == "法师":
            job = "\n🪄法师🪄"
        elif data["一转"] == "牧师":
            job = "\n🙏牧师🙏"
        elif data["一转"] == "刺客":
            job = "\n🗡️刺客🗡️"
    if "二转" in data:
        if data["二转"] == "泰坦":
            job = "\n🛡️泰坦🛡️"
        elif data["二转"] == "剑影":
            job = "\n⚔️剑影⚔️"
        elif data["二转"] == "魔导":
            job = "\n🪄魔导🪄"
        elif data["二转"] == "神官":
            job = "\n🙏神官🙏"
        elif data["二转"] == "影忍":
            job = "\n🗡️影忍🗡️"
        

    txt_attribute = ""
    if data["属性点"] > 0:
        txt_attribute = "\n➢可分配属性{}点[属性分配]".format(data["属性点"])

    bar_length = 10
    filled_length = int(round(bar_length * data["经验"]["当前"] / float(data["经验"]["最大"])))
    exp_bar = u"\u2588" * filled_length + u"\u2591" * (bar_length - filled_length)

    xiaoguo = ""
    if "特殊效果" in data:
        for xg in data["特殊效果"]:
            if "时限" not in xg:
                if "标记" in xg:
                    xiaoguo += "〈{}*{}〉".format(xg.split("*")[1], xg.split("*")[2])
                elif "体魄" not in xg and "血脉" not in xg and "天赋" not in xg:
                    xiaoguo += "〈{}〉".format(xg.split("*")[1])
                else:
                    continue
            else:
                results0 = xg.split("*")
                have_time = int(60 * int(results0[3]) + int(float(results0[2])) - int(float(time.time())))
                xiaoguo += "〈{}({}秒)〉".format(results0[1], have_time)

    txt = "\n===❈个人属性❈===\n【昵称：{}】{}\n◈等级 Lv.{} ({}/{})\n{}\n🍗{}\n————————————{}\n◈体质 {}  ◈敏捷 {}\n◈力量 {}  ◈智力 {}\n◈生命 {}/{}\n◈魔力 {}/{}\n◈物攻 {}  ◈魔攻 {}\n◈物防 {}  ◈魔防 {}\n◈命中 {}({}%)\n◈闪避 {}({}%)\n◈暴击 {}  ◈暴伤 {}\n◈暴免 {}  ◈暴抗 {}\n◈韧性 {}  ◈速度 {}\n◈生命回复 {}%\n◈魔力回复 {}%\n◈物理增伤 {}%\n◈魔法增伤 {}%\n◈物理减伤 {}%\n◈魔法减伤 {}%\n————————————\n◈体魄 {}\n◈血脉 {}\n◈天赋 {}\n————————————\n✪当前效果✪ {}".format(data["nickname"], job, data["等级"], data["经验"]["当前"], data["经验"]["最大"], exp_bar, data["体力"], txt_attribute, data["体质"]["最终"], data["敏捷"]["最终"], data["力量"]["最终"], data["智力"]["最终"], data["生命"]["当前"], data["生命"]["当前最大"], data["魔力"]["当前"], data["魔力"]["当前最大"], data["物攻"]["当前"], data["魔攻"]["当前"], data["物防"]["当前"], data["魔防"]["当前"], data["命中"]["当前"], data["最低命中率"], data["闪避"]["当前"], data["最低闪避率"], data["暴击"]["当前"], data["暴伤"]["当前"], data["暴免"]["当前"], data["暴抗"]["当前"], data["韧性"]["当前"], data["速度"]["当前"], data["生命回复"], data["魔力回复"], data["物理增伤"], data["魔法增伤"], data["物理减伤"], data["魔法减伤"], body, blood, talent, xiaoguo)

    await send_message(message, 0, 1, txt)
    return

async def my_equip(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid
    elif hasattr(message.author, 'user_openid'):
        number = message.author.user_openid
    uid = await player_id(number)
    with open(f"data/bag/{uid}.txt", 'r') as f:
        data = json.load(f)
    txt = "\n===❈个人装备❈===".format(data["nickname"])
    for key, value in data["装备"].items():
        if value:
            if "·" in value and "+" in value:
                txt0 = "\n"
                equip_have = value.split("=")
                value = value.split("+")[0]
                equip_have_split = equip_have[1].split("&")
                equip_have_number = len(equip_have_split)
                for random_num in range(1, equip_have_number):
                    txt0 += "[{}+{}]".format((equip_have_split[random_num - 1].split("*"))[0], (equip_have_split[random_num - 1].split("*"))[1])
                txt += "\n◈【{}】[{}]{}".format(key, value, txt0)
            else:
                txt += "\n◈【{}】[{}]".format(key, value)
        else:
            txt += "\n◈【{}】无".format(key)

    await send_message(message, 0, 1, txt)
    return

async def my_skill(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid 
    elif hasattr(message.author, 'user_openid'):    
        number = message.author.user_openid
    uid = await player_id(number)
    with open(f"data/player/{uid}.txt", 'r') as f:
        data = json.load(f)
    txt = "\n===❈个人技能❈===\n————————————".format(data["nickname"])
    
    txt += "\n【已装备({})】".format(data["装备技能"]["数量"])
    for key, value in data["装备技能"].items():
        if value:
            for item in data["学会技能"]:
                if item["名称"] == value:
                    txt += "\n◈[{}]===[{}•Lv.{}]".format(key, value, item["等级"])
                    break
    
    txt += "\n————————————\n【已学会】"
    for item in data["学会技能"]:
        txt += "\n◈[{}•Lv.{}]".format(item["名称"], item["等级"])
    
    await send_message(message, 0, 1, txt)
    return


async def search_all(message):
    name = message.content.split("全局搜索")[1]
    txt = ""
    i = 0
    try:
        if "·" in name:
            name0 = name.split("·")[0]
        else:
            name0 = name
        with open(f"data/equipment/{name0}.txt", 'r') as f:
            data = json.load(f)
            if data:
                i += 1
                shuxing = "｜".join([f"{k} {v}" for k, v in data["属性"].items()])
                if "套装" in data:
                    taozhuang = "｜".join(data["套装"])
                else:
                    taozhuang = "【无】"

                txt += "\n◈{}◈【装备】\n[名称] {}\n[部位] {}\n[属性] {}\n[简介] {}\n[套装] {}".format(i, data["名称"], data["部位"], shuxing, data["简介"], taozhuang)

    except FileNotFoundError:
        pass

    try:
        with open(f"data/monster/{name}.txt", 'r') as f:
            data = json.load(f)
            if data:
                i += 1
                skills = "｜".join([v.get("名称", "") for k, v in data["技能"].items() if k.startswith("技能")])
                unique_result = []
                for item in data["掉落"]:
                    if item["名称"] not in unique_result:
                        unique_result.append(item["名称"])
                result = "｜".join(unique_result)
                txt += "\n◈{}◈【怪物】\n[名称] {}\n[类别] {}\n[力量] {}({})[{}]\n[智力] {}({})[{}]\n[体质] {}({})[{}]\n[敏捷] {}({})[{}]\n[技能] {}\n[掉落] {}".format(i, data["名称"], data.get("一转", "无"), data["力量"]["基础"], data["力量"]["成长"], data["力量"].get("强度", 0), data["智力"]["基础"], data["智力"]["成长"], data["智力"].get("强度", 0), data["体质"]["基础"], data["体质"]["成长"], data["体质"].get("强度", 0), data["敏捷"]["基础"], data["敏捷"]["成长"], data["敏捷"].get("强度", 0), skills, result)
    except FileNotFoundError:
        pass
    
    try:
        with open(f"data/skills/{name}.txt", 'r') as f:
            data = json.load(f)
            if data:
                i += 1
                effect = "｜".join([item["名称"] for item in data["效果"]])
                txt += "\n◈{}◈【技能】\n[名称] {}\n[类别] {}\n[属性] {}\n[对象] {}\n[威力] {}\n[蓝耗] {}\n[冷却] {}\n[效果] {}".format(i, data["名称"], data["类别"], data["属性"], data["对象"], data["威力"], data["蓝耗"], data.get("冷却", 0), effect)
    except FileNotFoundError:
        pass
    txt_result = "\n【✡已搜索到[{}]条结果✡】\n————————————————".format(i) + txt

    #统计数量
    directory = "data/bag/"
    max_player = {}
    sum_num = 0
    for filename in os.listdir(directory):
        if filename.endswith(".txt"):
            filepath = os.path.join(directory, filename)
            with open(filepath, 'r') as f:
                data = json.load(f)
            count = 0
            for equipment in data["装备"].values():
                if equipment == name:
                    count += 1
                    break
            for thing in data["背包"]:
                if thing["名称"] == name:
                    count += int(thing["数量"])
                    break
            sum_num += count
            if len(max_player) < 3:
                max_player[data["nickname"]] = count
            else:
                smaller_vals = [val for val in max_player.values() if val < count]
                if smaller_vals:
                    # 如果存在比 count 小的值，则删除最小的那个键值对
                    min_val = min(smaller_vals)
                    key_to_delete = next(key for key, val in max_player.items() if val == min_val)
                    del max_player[key_to_delete]
                    max_player[data["nickname"]] = count

    txt_result += "\n————————————————\n【全服数量[{}]】\n排名：".format(sum_num)
    sorted_players = sorted(max_player.items(), key=lambda x: x[1], reverse=True)
    # 输出前三名或已有的项
    for i, (name, score) in enumerate(sorted_players):
        if i < 3 and i < len(max_player):
            txt_result += "\n<{}> {} [{}]".format(i+1, name, score)
        else:
            break

    await send_message(message, 0, 1, txt_result)
    return 

async def make_list(message):
    txt = "\n===❈制作列表❈==="
    page = re.search(r"\d+", message.content)
    if not page:
        page = 1
    else:
        page = int(page.group())
    with open(f"data/make.txt", 'r') as f:
        data = json.load(f)
    items_per_page = 20
    max_page = math.floor(len(data) / 20) + 1
    if page > max_page:
        txt = f"\n【页码错误！】\n【最大只有{max_page}页嗷！】"
        await send_message(message, 0, 1, txt)
        return
    start_index = (page - 1) * items_per_page
    end_index = start_index + items_per_page
    if end_index >= len(data):
        end_index = len(data)
    for item in data[start_index:end_index]:
        txt += "\n【{}】".format(item["名称"])
    if max_page > 1:
        txt += f"\n————————————\n第{page}页，共{max_page}页。发送[制作列表{page+1}]查看下一页。"
    await send_message(message, 0, 1, txt)
    return 



async def make_infor(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid 
    elif hasattr(message.author, 'user_openid'):    
        number = message.author.user_openid
    txt = "\n===❈制作信息❈==="
    uid = await player_id(number)
    make_name = message.content.split("制作信息")[1]
    found = False
    with open("data/make.txt", 'r') as f:
        make_data = json.load(f)
    with open(f"data/bag/{uid}.txt", 'r') as f:
        bag_data = json.load(f)
    
    for item in make_data:
        if item["名称"] == make_name:
            found = True
            txt += "\n【{}】".format(make_name)
            for method_idx, method in enumerate(item["配方"]):
                txt += "\n配方[{}]".format(str(method_idx+1))
                if isinstance(method, dict):
                    for key, value in method.items():
                        bag_number = 0
                        for bag_thing in bag_data["背包"]:
                            if bag_thing["名称"] == key:
                                bag_number = bag_thing["数量"]
                                break
                        txt += "\n[{}] × {} (拥有{})".format(key, value, bag_number)
                elif isinstance(method, list):
                    for material in method:
                        for key, value in material.items():
                            bag_number = 0
                            for bag_thing in bag_data["背包"]:
                                if bag_thing["名称"] == key:
                                    bag_number = bag_thing["数量"]
                                    break
                            txt += "\n[{}] × {} (拥有{})".format(key, value, number)
            break
    if not found:
        txt = "\n【不存在此物品的制作信息！】"
    else:
        await send_message(message, 0, 1, txt)
        return


async def my_job(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid
    elif hasattr(message.author, 'user_openid'):
        number = message.author.user_openid
    uid = await player_id(number)
    with open(f"data/player/{uid}.txt", 'r') as f:
        data = json.load(f)
    jobs = data["副职业"]
    txt = "\n===❈副职业信息❈===\n【{}】\n————————————".format(data["nickname"])
    for job in jobs:
        if job["副职业"] == "分解师":
            bar_length = 10
            filled_length = int(round(bar_length * job["熟练度"] / float(job["熟练度上限"])))
            exp_bar = u"\u2588" * filled_length + u"\u2591" * (bar_length - filled_length)
            txt += "\n职业 🪚分解师🪚\n精力 {}\n等级 Lv.{}({}/{})\n{}\n————————————\n【配备】\n工作台 [{}]\n工具 [{}]\n助具 [{}]\n————————————\n【发送[分解 物品名]进行分解】".format(job["精力"], job["等级"], job["熟练度"], job["熟练度上限"], exp_bar, job["装备"]["工作台"], job["装备"]["工具"], job["装备"]["助具"])
        elif job["副职业"] == "炼金师":
            bar_length = 10
            filled_length = int(round(bar_length * job["熟练度"] / float(job["熟练度上限"])))
            exp_bar = u"\u2588" * filled_length + u"\u2591" * (bar_length - filled_length)
            txt += "\n职业 ⚗️炼金师⚗️\n精力 {}\n等级 Lv.{}({}/{})\n{}\n————————————\n【配备】\n容器 [{}]\n工具 [{}]\n助具 [{}]\n————————————\n【发送[炼金 x*数&y*数&z*数]进行制作】\n【发送[批量炼金 x*数&y*数&z*数+次数]批量制作】".format(job["精力"], job["等级"], job["熟练度"], job["熟练度上限"], exp_bar, job["装备"]["容器"], job["装备"]["工具"], job["装备"]["助具"])
        elif job["副职业"] == "锻造师":
            bar_length = 10
            filled_length = int(round(bar_length * job["熟练度"] / float(job["熟练度上限"])))
            exp_bar = u"\u2588" * filled_length + u"\u2591" * (bar_length - filled_length)
            txt += "\n职业 🛠️锻造师🛠️\n精力 {}\n等级 Lv.{}({}/{})\n{}\n————————————\n【配备】\n锻炉 [{}]\n锻锤 [{}]\n锻具 [{}]\n————————————\n【发送[附魔 装备名*材料名*数量*拟名]进行初次附魔】\n【发送[附魔 装备全名*材料名*数量]进行二次附魔】".format(job["精力"], job["等级"], job["熟练度"], job["熟练度上限"], exp_bar, job["装备"]["熔炉"], job["装备"]["锻锤"], job["装备"]["锻具"])
    await send_message(message, 0, 1, txt)
    return

            
async def my_task(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid
    elif hasattr(message.author, 'user_openid'):
        number = message.author.user_openid
    uid = await player_id(number)
    with open(f"data/player/{uid}.txt", 'r') as f:
        data = json.load(f)
    txt = "\n===❈我的任务❈==="
    with open(f"data/冒险者公会_委托板.txt", 'r') as f:
        task_data = json.load(f)
    new_tasks = []
    for task in data["任务"]:
        if task["来源"] == "冒险者公会" and "等级评定" not in task["名称"]:
            if any(in_task["编码"] == task["编码"] for in_task in task_data["当前"]):
                new_tasks.append(task)
                continue
        else:
            new_tasks.append(task)

    data["任务"] = new_tasks

    for index, task in enumerate(data["任务"]):
        txt0 = ""
        if task.get("是否完成", "否") == "是":
            continue
        for item0 in task["目标"]:
            if item0["类型"] == "讨伐" or item0["类型"] == "单挑":
                txt0 += "\n            {}[{}]({}/{})".format(item0["类型"], item0["对象"], item0["已讨伐"], item0["数量"])
            elif item0["类型"] == "收集":
                thing_num = await bag_number(uid, item0["对象"])
                txt0 += "\n            {}[{}]({}/{})".format(item0["类型"], item0["对象"], thing_num, item0["数量"])
        txt0 = txt0.replace("\n            ", "", 1)
        if "事件*" in task["奖励"]:
            reward = task["奖励"].replace("事件*", "")
        else:
            reward = task["奖励"].replace("+", "、")

        item_index = ""
        time = ""
        if task["来源"] == "冒险者公会" and "等级评定" not in task["名称"]:
            for index, item in enumerate(task_data["当前"]):
                if item['编码'] == task['编码']:
                    item_index = "【{}】".format(index + 1)
                    time = "{}小时".format(item["剩余时间"])
                    break

        else:
            item_index = " ➤ "
            time = "无期限"

        txt += "\n{}{}\n委托方：{}\n类型：{}\n目标：{}\n奖励：{}\n剩余时间：{}".format(item_index, task["名称"], task["来源"], task["类型"], txt0, reward, time)
    with open(f"data/player/{uid}.txt", 'w') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
    await send_message(message, 0, 1, txt)
    return


async def my_evolute(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid
    elif hasattr(message.author, 'user_openid'):
        number = message.author.user_openid
    uid = await player_id(number)
    with open(f"data/player/{uid}.txt", 'r') as f:
        data = json.load(f)
    if int(data["灵阶"]) < 3:
        result_txt = "\n【你尚未开启进化！】"
        await send_message(message, 0, 1, result_txt)
        return
    txt = "\n===❈进化面板❈==="
    body = ["头", "身", "手", "脚"]
    for body1 in body:
        txt += "\n【{}】".format(body1)
        find = False
        for evolute in data["进化"]:
            if evolute["部位"] == body1:
                find = True
                txt += "\n[{}]\n{}+{}%".format(evolute["词条"], evolute["属性"], evolute["数值"])
        for evolute in data["进化诅咒"]:
            if evolute["部位"] == body1:
                find = True
                txt += "\n[{}]\n{}-{}%".format(evolute["词条"], evolute["属性"], evolute["数值"])
        if not find:
            txt += "\n[未进化]"
        txt += "\n————————————"
    lines = txt.split('\n')[:-1]
    result_txt = '\n'.join(lines)
    await send_message(message, 0, 1, result_txt)
    return


async def work_player_list(message):
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid
    elif hasattr(message.author, 'user_openid'):
        number = message.author.user_openid
    page = message.content.split("列表")[1]
    work_name = message.content.split("列表")[0]
    if not page:
        page = 1
    else:
        page = int(page)
        if page <= 0:
            page = 1
    directory = "data/player/"
    work_list = []
    for filename in os.listdir(directory):
        if filename.endswith(".txt"):
            filepath = os.path.join(directory, filename)
            with open(filepath, 'r') as f:
                data = json.load(f)
            if "副职业" in data:
                for work in data["副职业"]:
                    work_list.append({"昵称": data["nickname"], "uid": data["id"], "副职业": work["副职业"], "副等级": work["等级"]})
    allwork_list = [in_list for in_list in work_list if in_list["副职业"] == work_name]
    allwork_list.sort(key=lambda x: (x["副等级"], -x["uid"]), reverse=True)
    per_page = 10  # 每页显示的项数
    max_page = math.ceil(len(allwork_list) / per_page)
    if page > 1 and page > max_page:
        page = max_page
    start = (page - 1) * per_page  # 计算起始索引
    end = start + per_page  # 计算结束索引
    end = min(end, len(allwork_list))
    if work_name == "炼金师":
        picture = "⚗️"
        txt0 = "\n【发送[委托uid炼金 主材*数量&辅材*数量&催化剂*数量+次数]委托炼金】\n【示例】[委托1炼金天空粉尘*4&&+1]\n【基础费用】[10铜币/次]"
    elif work_name == "分解师":
        picture = "🪚"
        txt0 = "\n【发送[委托uid分解 物品*数量]委托分解】\n【示例】[委托1分解兽肉*1]\n【基础费用】[5铜币/个]"
    elif work_name == "锻造师":
        picture = "🛠️"
        txt0 = "\n【发送[委托uid附魔 装备*材料*数量*拟名]委托附魔】\n【示例】[委托1附魔树枝*白晶*1*毁灭]\n【基础费用】[50铜币/次]"
    txt = "\n===❈{}列表❈===".format(work_name)
    for index, player in enumerate(allwork_list[start:end], start=start):
        txt += "\n【{}】{}[uid:{}]\n      {}{}级{}{}".format(index+1, player["昵称"], player["uid"], picture, player["副等级"], work_name, picture)
    txt += "\n————————————" + txt0
    await send_message(message, 0, 1, txt)
    return